#!/bin/bash

PARAMETERS="";
DOCKER="";
HELP="false";

while [ "$1" != "" ]; do

	if [ "$1" == "-?" ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
		HELP="true";
		DOCKER="true";
		PARAMETERS="$PARAMETERS -ht opensource-install.sh";
	fi

	PARAMETERS="$PARAMETERS ${1}";
	shift
done

PARAMETERS="$PARAMETERS -os true -ed false";

command_exists () {
	type "$1" &> /dev/null;
}

install_sudo () {
	if command_exists apt-get; then
		apt-get install sudo
	elif command_exists yum; then
		yum install sudo
	fi

	if ! command_exists sudo; then
		echo "command sudo not found"
		exit 1;
	fi
}

install_curl () {
	if command_exists apt-get; then
		sudo apt-get -y update
		sudo apt-get -y -q install curl
	elif command_exists yum; then
		sudo yum -y install curl
	fi

	if ! command_exists curl; then
		echo "command curl not found"
		exit 1;
	fi
}

read_installation_method () {
	echo "Select 'Y' to install ONLYOFFICE using Docker (recommended). Select 'N' to install it using RPM/DEB packages.";
	echo "Please note, that in case you select RPM/DEB installation, you will need to manually install Mail Server and connect it to your ONLYOFFICE installation.";
	echo "See instructions in our Help Center: http://helpcenter.onlyoffice.com/server/docker/mail/connect-mail-server-to-community-server-via-portal-settings.aspx";
	echo "Install with Docker [Y/N/C]? n";
	DOCKER="false";

	if [ "$DOCKER" == "" ]; then
		read_installation_method;
	fi
}

if ! command_exists sudo ; then
	install_sudo;
fi

if ! command_exists curl ; then
	install_curl;
fi

if [ "$HELP" == "false" ]; then
	read_installation_method;
fi


if [ -f /etc/redhat-release ] ; then
	DIST=$(cat /etc/redhat-release |sed s/\ release.*//);
	REV=$(cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//);

	REV_PARTS=(${REV//\./ });
	REV=${REV_PARTS[0]};

	if [[ "${DIST}" == CentOS* ]] && [ ${REV} -lt 7 ]; then
		echo "CentOS 7 or later is required";
		exit 1;
	fi

	sudo bash install-RedHat.sh ${PARAMETERS}
elif [ -f /etc/debian_version ] ; then
	sudo bash install-Debian.sh ${PARAMETERS}
else
	echo "Not supported OS";
	exit 1;
fi
